package com.zzz.demo.format;


import com.alibaba.fastjson.JSON;
import com.github.vertical_blank.sqlformatter.SqlFormatter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SqlFormatTool {
    public static String genSQL(String preparing, String parameters) {
        try {
            preparing = initPreparing(preparing);
            List<String> paramList = JSON.parseArray(parameters, String.class);
            for (String param : paramList) {
                String resultParam = param;
                int index = param.indexOf("(");
                if (index != -1)
                    resultParam = resultParam.substring(0, index).trim();
                if (param.contains("(String)"))
                    resultParam = String.format("'%s'", resultParam);
                if (param.contains("(BigDecimal)"))
                    resultParam = (new DecimalFormat("#.########")).format(new BigDecimal(resultParam));
                if (param.contains("(Timestamp)")) {
                    index = param.indexOf(".");
                    if (index != -1)
                        resultParam = resultParam.substring(0, index - 1);
                    resultParam = String.format("'%s'", resultParam);
                }

                // 去除\" 和 "
                resultParam = resultParam.replaceAll("\\\"", "").replaceAll("\"", "");
                if (resultParam.endsWith(".000")) {
                    resultParam = resultParam.substring(0, resultParam.length() - 4);
                }
                preparing = preparing.replaceAll("TO_DATE\\(TO_CHAR\\(\\?, 'yyyy-MM-dd hh24:mi:ss'\\), 'yyyy-MM-dd hh24:mi:ss'\\)", "TO_DATE(?, 'yyyy-MM-dd hh24:mi:ss')");
                if (!StringUtils.isNumeric(resultParam)) {
                    preparing = preparing.replaceFirst("\\?", "'" + resultParam + "'");
                } else {
                    preparing = preparing.replaceFirst("\\?", resultParam);
                }
            }
            preparing = preparing.replace("\n", " ").replaceAll("\\s+", " ");
            return SqlFormatter.format(preparing);
        } catch (Exception e) {
            e.printStackTrace();
            return "gen preparing error:" + e.getMessage();
        }
    }

    public static String initPreparing(String sql) {
        if (StringUtils.isBlank(sql))
            return "";
        String result = "";
        int index = sql.indexOf("Preparing: ");
        if (index != -1) {
            result = sql.substring(index).replace("Preparing:", "").trim();
        } else {
            result = sql;
        }
        result = result.replace("&gt;", ">").replace("&lt;", "<");
        String methodName = "";
        int index2 = sql.indexOf("]");
        if (index2 != -1 && index != -1)
            methodName = sql.substring(index2 + 1, index).trim();
        if (StringUtils.isNotBlank(methodName))
            result = methodName + result;
        return result;
    }

    public static String initParameters(String param) {
        if (StringUtils.isBlank(param))
            return "";
        String result = "";
        int index = param.indexOf("Parameters: ");
        if (index != -1) {
            result = param.substring(index).replace("Parameters:", "").trim();
        } else {
            result = param;
        }
        result = result.replace("[", "").replace("]", "").replace("\"", "'");
        return result;
    }

    public static String format(String text) {
        List<String> logs = Arrays.asList(text.split("\n"));
        if (CollectionUtils.isEmpty(logs))
            return "";
        List<String> preparingList = new ArrayList<>();
        List<String> parametersList = new ArrayList<>();
        logs.forEach(log -> {
            if (log.contains(": ==>  Preparing: ")) {
                preparingList.add(log);
            } else if (log.contains(": ==> Parameters:")) {
                parametersList.add(log);
            }
        });
        if (CollectionUtils.isEmpty(preparingList))
            return text;
        String result = "";
        for (int i = 0; i < preparingList.size(); i++) {
            String sql = genSQL(preparingList.get(i), parametersList.get(i));
            sql = sql.replace(": ==>", "\r\n");
            sql = sql.replace("FROM", "\r\nFROM");
            sql = sql.replace("WHERE", "\r\nWHERE");
            result = String.valueOf(result) + String.format("-- %s;\r\n", new Object[]{Integer.valueOf(i + 1), sql});
        }
        return result;
    }

    public static void main(String[] args) {
        String a = "\\\"";
        System.out.println(a);
    }
}

